package com.anyonavinfo.cpaddemo.utils.killprocessutils;

import android.app.ActivityManager;
import android.content.Context;
import android.text.format.Formatter;
import android.widget.Toast;

import com.anyonavinfo.cpaddemo.utils.killprocessutils.models.AndroidAppProcess;

import java.util.List;

/**
 * Created by ZuiC on 2017/2/7.
 */

public class KillProcessUtils {
    private Context mContext;

    public KillProcessUtils(Context context){
        mContext = context;
    }

    public void killProcess(){
        long beforeMem = getAvailMemory(mContext);//清理前的可用内存
        //获取一个ActivityManager 对象
        ActivityManager activityManager = (ActivityManager)
                mContext.getSystemService(Context.ACTIVITY_SERVICE);
        //统计杀死的进程数
        int count=0;

        //获取包名信息
        List<AndroidAppProcess> processInfos = ProcessManager.getRunningAppProcesses();
        // 遍历运行的程序,并且获取其中的信息
        for (AndroidAppProcess processInfo : processInfos) {
            // 应用程序的包名
            String packname = processInfo.name;
            if( !packname.contains("com.android.system")&&
                    !packname.contains("com.anyonavinfo.bluetoothphone")&&
                    processInfo.pid!=android.os.Process.myPid()&&
                    !packname.equals("com.com.autopet.hardware.aidl") &&
                    !packname.equals("com.wedrive.welink.sgmw.navigation")&&
                    !packname.equals("com.tencent.qqmusicpad")){
                activityManager.killBackgroundProcesses(packname);//杀死该进程
                count++;//杀死进程的计数+1
            }
        }
        long afterMem = getAvailMemory(mContext);//清理后的内存占用
        Toast.makeText(mContext, "已清理 " + (count) + " 个进程, 释放"
                + formatFileSize(afterMem - beforeMem) + "内存", Toast.LENGTH_LONG).show();
    }

    private long getAvailMemory(Context context) {
        // 获取android当前可用内存大小
        ActivityManager am = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
        ActivityManager.MemoryInfo mi = new ActivityManager.MemoryInfo();
        am.getMemoryInfo(mi);
        return mi.availMem;
    }

    private String formatFileSize(long number){
        return Formatter.formatFileSize(mContext, number);
    }

}
